package com.atguigu.tingshu.payment.api;

import com.atguigu.tingshu.common.login.GuiGuLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.wechat.pay.java.service.refund.model.Refund;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "微信支付接口")
@RestController
@RequestMapping("api/payment")
@Slf4j
public class WxPayApiController {

    @Autowired
    private WxPayService wxPayService;


    /**
     * 获取小程序拉起微信支付所需参数
     *
     * @param paymentType 支付类型 1301-订单 1302-充值
     * @param orderNo     交易订单号或充值订单号
     * @return {"timeStamp":"","package":"","paySign":"","signType":"RSA","nonceStr":""}
     */
    @Operation(summary = "获取小程序拉起微信支付所需参数")
    @PostMapping("/wxPay/createJsapi/{paymentType}/{orderNo}")
    public Result<Map<String, String>> createJsapi(
            @PathVariable("paymentType") String paymentType,
            @PathVariable("orderNo") String orderNo
    ) {
        //1.获取用户ID
        Long userId = AuthContextHolder.getUserId();
        //2.调用支付业务层对接微信
        Map<String, String> map = wxPayService.createJsapi(userId, paymentType, orderNo);
        return Result.ok(map);
    }


    /**
     * 查询订单交易状态
     *
     * @param orderNo
     * @return
     */
    @GuiGuLogin
    @Operation(summary = "查询订单交易状态")
    @GetMapping("/wxPay/queryPayStatus/{orderNo}")
    public Result<Boolean> queryPayStatus(@PathVariable("orderNo") String orderNo) {
        //1.调用微信查询订单状态
        boolean result = wxPayService.queryPayStatus(orderNo);
        return Result.ok(result);
    }

    /**
     * 用户付款成功后，微信支付回调接口
     *
     * @param request
     * @return {code:"SUCCESS",message:"支付成功"}
     */
   /* @Operation(summary = "用户付款成功后，微信支付回调接口")
    @PostMapping("/wxPay/notify")
    public Result<Map<String, String>> notifyPayResult(HttpServletRequest request) {
        Map<String, String> map = wxPayService.notifyPayResult(request);
        return Result.ok(map);
    }*/


    /**
     * 发起退款
     *
     * @param orderNo
     * @return
     */

    @Operation(summary = "发起退款")
    @GetMapping("/wxPay/closeWxPay/{orderNo}")
    public Result<Refund> closeWxPay(@PathVariable("orderNo") String orderNo) {
        wxPayService.closeWxPay(orderNo);
        return Result.ok();
    }

    /**
     * 发起退款
     *
     * @param orderNo
     * @return
     */

    @Operation(summary = "发起退款")
    @GetMapping("/wxPay/refunds/{orderNo}")
    public Result<Refund> refunds(@PathVariable("orderNo") String orderNo) {
        Refund refund = wxPayService.refunds(orderNo);
        return Result.ok(refund);
    }
}
